#include "GameWinLayer.h"
#include "GameScene.h"
#include "Scene\MenuScene\MenuScene.h"

GameWinLayer* GameWinLayer::createLayer(int currentLevel) {
	GameWinLayer *layer = new GameWinLayer();
	if (layer && layer->initLayer(currentLevel)) {
		layer->autorelease();
		return layer;
	}
	CC_SAFE_DELETE(layer);
	return nullptr;
}

bool GameWinLayer::initLayer(int currentLevel) {
	if (!Layer::init()) return false;
	m_currentLevel = currentLevel;
	if (m_currentLevel == USERDEFAULT->getIntegerForKey(LEVEL_KEY)) {
		Player::getInstance()->setLevel(currentLevel + 1);
	}

	AUDIOENGINE->preloadBackgroundMusic(GAMEWIN_BGM_NAME);
	auto rootNode = CSLoader::createNode(GAMEWINLAYER_CSB_NAME);
	this->addChild(rootNode);
	auto action = CSLoader::createTimeline(GAMEWINLAYER_CSB_NAME);
	rootNode->runAction(action);
	action->gotoFrameAndPlay(0, false);

	if (USERDEFAULT->getBoolForKey(EFFECT_ENABLE_KEY)) {
		AUDIOENGINE->stopAllEffects();
		AUDIOENGINE->stopBackgroundMusic();
		AUDIOENGINE->playEffect(GAMEWIN_BGM_NAME);
	}

	auto text = rootNode->getChildByName<Text *>(WIN_TEXT);
	auto homeButton = rootNode->getChildByName<Button *>(WIN_HOMEBUTTON);
	auto retryButton = rootNode->getChildByName<Button *>(WIN_RETRYBUTTON);
	auto nextButton = rootNode->getChildByName<Button *>(WIN_NEXTBUTTON);

	text->setFontName(TEXTFONT_NAME);
	retryButton->addClickEventListener([=](Ref *ref) {
		DIRECTOR->replaceScene(TransitionCrossFade::create(1, GameScene::createScene(m_currentLevel)));
	});
	homeButton->addClickEventListener([=](Ref *ref) {
		DIRECTOR->replaceScene(MenuScene::createScene());
	});
	nextButton->addClickEventListener([=](Ref *ref) {
		DIRECTOR->replaceScene(TransitionCrossFade::create(1, GameScene::createScene(m_currentLevel + 1)));
	});

	return true;
}